package com.bjc.chapter16.reference;

import java.lang.ref.WeakReference;

/**
 * @program: jvm_demo
 * @description: 弱引用
 * @author: bjc
 * @create: 2022-02-17 22:16
 */
public class WeakReferenceTest {

    public static class User{
        public int id;
        public String name;

        public User(int id, String name) {
            this.id = id;
            this.name = name;
        }

        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    '}';
        }
    }

    public static void main(String[] args) {
        //构造了弱引用
        WeakReference userWeakRef = new WeakReference<User>(new User(1, "cm"));
        //从弱引用中重新获取对象
        System.out.println(userWeakRef.get());

        System.gc();
        //不管当前内存空间足够与否，都会回收他的内存
        System.out.println("After GC");
        //重新尝试从弱引用中获取对象
        System.out.println(userWeakRef.get());
    }
}
